<?php

namespace app\api\controller;
use fast\Random;
use app\common\controller\Api;

/**
 * 二手房收藏房源接口
 */
class Secondfavorate extends Api
{

    // 无需登录的接口,*表示全部
    protected $noNeedLogin = [];
    // 无需鉴权的接口,*表示全部 //TODO: 这里暂时不鉴权，以后要改
    protected $noNeedRight = [];
    /**
     * Items模型对象
     * @var \app\common\model\UserFavorate
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\UserFavorate;

    }
   
    /**
     * @ApiTitle (收藏房源)
     * @ApiSummary (二手房使用)
     * @ApiMethod (Post)
     * @ApiRoute (/api/secondfavorate/addfavorate)
     * @ApiParams (name="ids", type="string", required=false, description="房源编号")
     * @ApiReturn ({
            'code':'1',
            'msg':'返回成功'
      })
     */
    public function addfavorate(){
        $ids = $this->request->post('ids');
        if(empty($ids)){
            $this->error('参数错误');
        }
        $target='二手房出售房源';
        $housemodel = $this->getSecondItem($ids);

        if($housemodel==null){
            $this->error('要收藏的房源不存在');
        }

        $model = new \app\common\model\UserFavorate;
        //是否已经收藏了
        $list=$model->where(['user_id'=>$this->auth->id,'target'=>$target,'target_id'=>$ids])->select();
        if(!empty($list)){
            $this->error('要收藏的房源已存在');
        }
        $model = new \app\common\model\UserFavorate;
        $model->fav_id =str_replace('-','',  Random::uuid());
        $model->user_id = $this->auth->id;
        $model->target = $target;
        $model->target_id = $ids;
        $model->create_time = date('Y-m-d',time());
        $model->create_ip = '';
        $model->comment = $housemodel['building']->building_name . ' 面积:' . $housemodel['item']->area;
        $model->save();
        $this->success('收藏房源操作成功');
    }
    /**
    * @ApiTitle (删除收藏房源)
    * @ApiSummary (二手房使用)
    * @ApiMethod (Post)
    * @ApiRoute (/api/secondfavorate/delfavorate)
    * @ApiParams (name="ids", type="string", required=false, description="房源编号")
    * @ApiReturn ({
           'code':'1',
           'msg':'返回成功'
    })
    */
    public function delfavorate(){
        $ids = $this->request->post('ids');
        $target='二手房出售房源';
        $model =  \app\common\model\UserFavorate::get(['user_id'=>$this->auth->id,'target_id'=>$ids,'target'=>$target]);
        if(empty($model)){
            $this->error('要删除收藏的房源不存在');
        }
        $model->delete();
        $this->success('删除收藏操作成功');
    }
    /**
     * @ApiTitle (获取收藏房源列表)
     * @ApiSummary (二手房使用)
     * @ApiMethod (Get)
     * @ApiRoute (/api/secondfavorate/list)
     * @ApiParams   (name="offset", type="integer", required=false, description="分页偏移值")
     * @ApiParams   (name="limit", type="integer", required=false, description="分页大小，默认15，最大50")
     * @ApiParams   (name="sort", type="string", required=false, description="排序字段")
     * @ApiParams   (name="order", type="string", required=false, description="排序顺序,asc或desc")
     */
    public function list(){

         //当前是否为关联查询
         $this->relationSearch = true;
         //设置过滤方法
         $this->request->filter(['strip_tags']);
     
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();

        $total = $this->model
            ->where($where)
            ->order($sort, $order)
            ->count();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->limit($offset, $limit)
            ->select()
            ;
    
        $list = collection($list)->toArray();
        $result = array("total" => $total, "rows" => $list);

        $this->success('查询收藏房源操作成功',$result);

    }
      /**
     * 查询一个房源
     */
    private function getSecondItem($ids){
        $model = new \app\common\model\SecondItems;

        $list = $model->with('seconddecoration')->where(['mf_second_items.id'=>$ids])->select();
        if(empty($list)){
            return null;
        }
        
        $ret=['item'=>$list[0]];
        
        // TODO: 权限限制
        // 跟进信息
        $followList = \app\common\model\SecondFollow::select(['item_id'=>$ids]);
        $ret['follow'] = $followList;
        // 楼盘信息
        $buildingItem = \app\common\model\SecondBuildings::get(['id'=>$list[0]->building_id]);
        $ret['building'] = $buildingItem;
        return $ret;
    }
}
